<template>
  <el-dialog
      modal-value="dialogVisible"
      title="分配角色"
      style="padding: 40px"
      width="600px"
      @close="handleClose"
      draggable
      overflow
  >
    <el-form
        ref="formRef"
        :model="form"
        label-width="100px"
    >
      <el-form-item label="选择角色:" prop="username">
        <el-checkbox-group v-model="form.checkedRoles">
          <el-checkbox v-for="item in form.roleList" :value='item.id' :id='item.id.toString()' :key='item.id' name="checkedRoles">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确 认</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, watch} from 'vue'
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  sysRoleList: {
    type: Array,
    default:()=> [],
    required: true
  },
  roleDialogVisible: {
    type: Boolean,
    default: false,
    required: true,
  }
})

const form = ref({
  id: -1,
  roleList: [],
  checkedRoles: [],
})

const formRef = ref(null)
const initFormData = async (id) => {
  const res = await requestUtil.get('role/check/roles');
  form.value.roleList = res.data.msg;
  console.log(res.data.msg,'-------form.value.roleList = res.data.msg')
  form.value.id = id;
}
initFormData()

watch(
    () => props.roleDialogVisible,
    () => {
      let id = props.id;
      if (id !== -1) {
        form.value.checkedRoles = [];
        props.sysRoleList.forEach(item => {
          form.value.checkedRoles.push(item.id)
        });
        initFormData(id);
      }
    }
)

const emits = defineEmits(['update:modelValue', 'initTableData'])

const handleClose = () => {
  emits('update:modelValue', false)
}
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = await requestUtil.post('user/grant/role', {'id': form.value.id, 'roleList': form.value.checkedRoles});
      let data = res.data;
      if (data.code === 200) {
        ElMessage.success('执行成功')
        formRef.value.resetFields();
        emits('initTableData');
        handleClose();
      } else {
        ElMessage.error(data.msg);
      }
    } else {
      console.log('fail')
    }
  })
}
</script>
